package com.itmumu.miniwechat.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itmumu.miniwechat.common.exception.BusinessException;
import com.itmumu.miniwechat.common.utils.ContextUtil;
import com.itmumu.miniwechat.common.utils.PinyinGroupUtil;
import com.itmumu.miniwechat.user.domain.dto.UserContactApplyDto;
import com.itmumu.miniwechat.user.domain.enums.*;
import com.itmumu.miniwechat.user.domain.po.User;
import com.itmumu.miniwechat.user.domain.po.UserContact;
import com.itmumu.miniwechat.user.domain.po.UserContactApply;
import com.itmumu.miniwechat.user.domain.vo.response.UserContactGroupVo;
import com.itmumu.miniwechat.user.domain.vo.response.UserInfoVo;
import com.itmumu.miniwechat.user.mapper.UserContactMapper;
import com.itmumu.miniwechat.user.service.UserContactService;
import com.itmumu.miniwechat.user.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.*;

/**
 * @author admin
 * @description 针对表【user_contact(用户联系人表)】的数据库操作Service实现
 * @createDate 2024-12-30 19:37:14
 */
@Service
public class UserContactServiceImpl extends ServiceImpl<UserContactMapper, UserContact>
        implements UserContactService {

    @Resource
    @Lazy
    private UserService userService;


    /**
     * 新增联系人记录
     */
    @Override
    public void addContact(UserContactApplyDto applyDto) {
        Integer applyUid = ContextUtil.getUserInfo().getUid();

        // TODO 群聊后续添加

        Date curDate = new Date();

        UserContact userContact = new UserContact();
        // uid小的作为联系人表中的uid
        userContact.setUid(applyUid < applyDto.getContactId() ? applyUid : applyDto.getContactId());
        userContact.setContactId(applyUid < applyDto.getContactId() ? applyDto.getContactId() : applyUid);
        userContact.setContactStatus(UserContactStatus.NOT_FRIEND.getCode());
        userContact.setSource(UserContactSource.SEARCH.getCode());

        // 填写备注信息
        if (applyUid < applyDto.getContactId()) {
            userContact.setRemark1(applyDto.getRemark());
        } else {
            userContact.setRemark2(applyDto.getRemark());
        }


    }


    /**
     * 根据uid和联系人id查询他们的好友关系记录
     *
     * @param uid
     * @param contactId
     * @return
     */
    public UserContact selectByUserIdAndContactId(Integer uid, Integer contactId) {
        // 查询用户联系人状态
        LambdaQueryWrapper<UserContact> userContactWrapper = new LambdaQueryWrapper<>();

        // 判断当前用户的uid是否小于查询的uid，因为数据库中的uid总是以小的那个存储
        if (uid < contactId) {
            userContactWrapper
                    .eq(UserContact::getUid, uid)
                    .eq(UserContact::getContactId, contactId);
        } else {
            userContactWrapper
                    .eq(UserContact::getUid, contactId)
                    .eq(UserContact::getContactId, uid);
        }
        userContactWrapper
                .eq(UserContact::getContactType, UserContactTypeEnum.FRIEND.getCode());
        return this.getOne(userContactWrapper);
    }


    /**
     * 初始化登录用户联系人
     */
    @Override
    public void initLoginUserContact(Integer uid) {
        // 查询用户是否已经初始化过一条记录
        LambdaQueryWrapper<UserContact> contactQuery = new LambdaQueryWrapper<>();
        contactQuery.eq(UserContact::getUid, uid)
                .eq(UserContact::getContactId, uid);

        UserContact currentUserContact = this.getOne(contactQuery);
        if (Objects.isNull(currentUserContact)) {
            UserContact contact = new UserContact();
            contact.setUid(uid);
            contact.setContactId(uid);
            contact.setContactType(UserContactTypeEnum.FRIEND.getCode());
            contact.setContactStatus(UserContactStatus.FRIEND.getCode());
            contact.setSource(UserContactSource.LOGIN.getCode());

            this.save(contact);
        }
    }

    @Override
    public void addContact(Integer applyUid, Integer receiveUid, Integer contactId, Integer contactType, String applyDesc) {

        // 判断是否是群聊
        if (Objects.equals(contactType, UserContactTypeEnum.GROUP)) {
            // 群聊的话需要判断上限
            LambdaQueryWrapper<UserContact> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserContact::getContactId, contactId);
            wrapper.eq(UserContact::getContactStatus, UserContactStatus.FRIEND.getCode());

            long count = this.count();
            if (count >= 200) {
                throw new BusinessException("联系人数量已达上限。");
            }
        }

        // 入库申请记录
        Date cur = new Date();
        ArrayList<UserContact> list = new ArrayList<>();

        UserContact userContact = new UserContact();
        userContact.setUid(applyUid);
        userContact.setContactId(contactId);
        userContact.setContactType(contactType);
        userContact.setContactStatus(UserContactStatus.FRIEND.getCode());
        list.add(userContact);

        //如果是申请好友 接收人添加申请人  群组不用添加对方为好友
        if (Objects.equals(UserContactTypeEnum.FRIEND.getCode(), contactType)) {
            userContact = new UserContact();
//            userContact.
        }
    }


    /**
     * 查询所有用户联系人，并进行分组
     * @return
     */
    @Override
    public UserContactGroupVo listUserContact() {
        Integer curUid = ContextUtil.getUserInfo().getUid();

        LambdaQueryWrapper<UserContact> friendWrapper = new LambdaQueryWrapper<>();
        friendWrapper
                .and(wp -> {
                    wp.eq(UserContact::getUid, curUid)
                            .or()
                            .eq(UserContact::getContactId, curUid);
                })
                .eq(UserContact::getContactStatus, UserContactStatus.FRIEND.getCode())
                .eq(UserContact::getIsBlocked, UserContactBlockEnum.NOT_BLOCKED)
                .eq(UserContact::getDeletedBy, 0)
                .orderBy(true, true, UserContact::getId);

        List<UserContact> userContacts = this.list(friendWrapper);

        UserContactGroupVo groupVo = new UserContactGroupVo();

        // 用户数据分组
        Map<String, List<UserInfoVo>> friendGroups = new HashMap<>();
        // 处理数据，将数据进行分组
        userContacts.stream().forEach(item -> {
            // 判断联系人的uid
            Integer contacId = Objects.equals(item.getUid(), curUid) ? item.getContactId() : item.getUid();

            // 判断类型
            if (Objects.equals(item.getContactType(), UserContactTypeEnum.FRIEND.getCode())) {
                // 查询用户信息
                User contactUser = userService.getById(contacId);

                // TODO 查询是否收藏了该用户
                UserInfoVo userInfoVo = new UserInfoVo();
                userInfoVo.setUid(contactUser.getUid());
                userInfoVo.setAvatar(contactUser.getAvatar());
                userInfoVo.setNickname(contactUser.getNickname());
                userInfoVo.setIsCollected(0);

                String initial = PinyinGroupUtil.getInitial(contactUser.getNickname());
                if (!friendGroups.containsKey(initial)) {
                    friendGroups.put(initial, new ArrayList<>());
                }

                // 添加到对应分组
                friendGroups.get(initial).add(userInfoVo);
            } else {
                // TODO 查询群组信息
            }
        });

        // 对friendGroups里面的每一项进行升序排序
        for (List<UserInfoVo> userInfoVoList : friendGroups.values()) {
            userInfoVoList.sort(Comparator.comparing(UserInfoVo::getNickname));
        }

        groupVo.setFriendGroup(friendGroups);

        // TODO 最后需要存入redis
        return groupVo;
    }
}




